const { post, handleTokenExpired } = require('./request.js');
const { 
  encryptLoginData, 
  decryptLoginResponse,
  generateKeyFingerprint, 
  checkCryptoLibs
} = require('./crypto-utils.js');

/**
 * 用户相关API
 */
const userApi = {
  getRsaPublicKey() {
    return post('/user/getRsaPublicKey');
  },

  login(params) {
    return post('/user/login', params);
  },

  logout() {
    return post('/user/logout');
  },

  getUserInfo() {
    return post('/user/info');
  }
};

/**
 * 将Base64公钥转换为PEM格式
 */
const formatPublicKeyToPEM = (base64Key) => {
  // 移除可能存在的空格和换行符
  const cleanKey = base64Key.replace(/\s/g, '');
  
  // 每64个字符换行（PEM标准格式）
  const formattedKey = cleanKey.match(/.{1,64}/g).join('\n');
  
  return `-----BEGIN PUBLIC KEY-----\n${formattedKey}\n-----END PUBLIC KEY-----`;
};

/**
 * 获取后端RSA公钥
 */
const getRsaPublicKey = async () => {
  try {
    const response = await userApi.getRsaPublicKey();
    
    if (response.code === 200 && response.data) {
      const rawPublicKey = response.data;

      
      // 检查是否为空或无效
      if (!rawPublicKey || typeof rawPublicKey !== 'string' || rawPublicKey.length < 50) {
        throw new Error('后端返回的公钥数据无效');
      }
      
      let publicKey;
      
      // 判断是否已经是PEM格式
      if (rawPublicKey.includes('BEGIN PUBLIC KEY')) {
        publicKey = rawPublicKey;
      } else {
        // 转换Base64格式为PEM格式
        publicKey = formatPublicKeyToPEM(rawPublicKey);
      }
      

      
      return {
        success: true,
        data: publicKey
      };
    } else {
      return {
        success: false,
        message: response.message || '获取公钥失败'
      };
    }
  } catch (error) {
    console.error('获取公钥失败:', error);
    return {
      success: false,
      message: error.message || '获取公钥失败，请检查网络连接'
    };
  }
};

/**
 * 加密登录
 */
const login = async (loginData) => {
  try {
    // 1. 检查加密库
    const libCheck = checkCryptoLibs();
    if (!libCheck.ready) {
      throw new Error('加密库未就绪，请确保已正确安装crypto-js和wxmp-rsa');
    }
    
    // 2. 获取后端RSA公钥
    const publicKeyResult = await getRsaPublicKey();
    if (!publicKeyResult.success) {
      throw new Error(publicKeyResult.message || '获取加密公钥失败');
    }
    
    // 3. 构建标准登录数据格式
    const standardLoginData = {
      username: loginData.username || '',
      phone: loginData.phone || '',
      account: loginData.account,
      password: loginData.password,
      type: loginData.type || 1
    };
    
    // 验证必需字段
    if (!standardLoginData.account || !standardLoginData.password || !standardLoginData.username) {
      throw new Error('账号、密码和姓名不能为空');
    }
    
    // 4. 加密登录数据
    const encryptedData = await encryptLoginData(standardLoginData, publicKeyResult.data);
    
    // 5. 发送加密登录请求
    const response = await userApi.login(encryptedData);
    
    if (response.code === 200 && response.data) {
      // 检查是否是加密响应
      if (response.data.encryptData && response.data.encryptKey) {
        
        // 解密响应数据
        const decryptResult = decryptLoginResponse(response.data);
        if (!decryptResult.success) {
          throw new Error('解密登录响应失败: ' + decryptResult.error);
        }
        
        // 从解密后的数据中提取token和其他信息
        const decryptedData = decryptResult.data;
        const token = decryptedData.token || decryptedData;
        const role = decryptedData.role;
        
        if (token) {
          // 保存token和用户信息
          wx.setStorageSync('token', token);
          
          const userInfo = {
            role,
            token,
            type: loginData.type,
            account: loginData.account,
            username: loginData.username,
            loginTime: new Date().getTime()
          };
          wx.setStorageSync('userInfo', userInfo);
          
          return {
            success: true,
            data: decryptedData,
            message: response.message || '登录成功'
          };
        } else {
          throw new Error('解密后的数据中缺少token');
        }
      } else {
        // 处理非加密响应（向后兼容）
        const token = response.data.token || response.data;
        const role = response.data.role;
        
        if (token) {
          // 保存token和用户信息
          wx.setStorageSync('token', token);
          
          const userInfo = {
            role,
            token,
            type: loginData.type,
            account: loginData.account,
            username: loginData.username,
            loginTime: new Date().getTime()
          };
          wx.setStorageSync('userInfo', userInfo);
          
          return {
            success: true,
            data: response.data,
            message: response.message || '登录成功'
          };
        } else {
          throw new Error('登录响应中缺少token');
        }
      }
    } else {
      return {
        success: false,
        message: response.message || '登录失败'
      };
    }
  } catch (error) {
    // 检查是否是token相关错误
    if (error.code === 401 || error.code === 403 || error.code === 1001 ||
        (error.message && (error.message.includes('token') || error.message.includes('Token') ||
         error.message.includes('登录') || error.message.includes('身份验证')))) {
      handleTokenExpired(error.message || 'Token已过期，请重新登录');
    }
    
    return {
      success: false,
      message: error.message || '登录失败，请检查网络连接'
    };
  }
};

/**
 * 获取完整用户信息
 */
const fetchUserInfo = async () => {
  try {
    const response = await userApi.getUserInfo();
    
    if (response.code === 200 && response.data) {
      const userInfo = response.data;
      
      const existingInfo = wx.getStorageSync('userInfo') || {};
      const completeUserInfo = {
        ...existingInfo,
        ...userInfo,
        name: userInfo.name,
        employeeNumber: userInfo.employeeNumber,
        phone: userInfo.phone,
        groupId: userInfo.groupId,
        leader: userInfo.leader,
        status: userInfo.status
      };
      
      wx.setStorageSync('userInfo', completeUserInfo);
      
      return {
        success: true,
        data: completeUserInfo,
        message: '获取用户信息成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '获取用户信息失败'
      };
    }
  } catch (error) {
    if (error.code === 401 || error.code === 403 || error.code === 1001 ||
        (error.message && (error.message.includes('token') || error.message.includes('Token') ||
         error.message.includes('登录') || error.message.includes('身份验证')))) {
      handleTokenExpired(error.message || 'Token已过期，请重新登录');
    }
    
    return {
      success: false,
      message: error.message || '获取用户信息失败'
    };
  }
};

/**
 * 登出
 */
const logout = async () => {
  try {
    await userApi.logout();
    
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    
    return {
      success: true,
      message: '登出成功'
    };
  } catch (error) {
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    
    return {
      success: false,
      message: error.message || '登出失败'
    };
  }
};

/**
 * 检查登录状态
 */
const checkLoginStatus = () => {
  const token = wx.getStorageSync('token');
  const userInfo = wx.getStorageSync('userInfo');
  
  return !!(token && userInfo);
};

/**
 * 强制登录检查
 */
const requireLogin = () => {
  if (!checkLoginStatus()) {
    wx.reLaunch({
      url: '/pages/login/login'
    });
    return false;
  }
  return true;
};

/**
 * 测试Token状态 - 调试用函数
 */
const testTokenStatus = () => {
  const token = wx.getStorageSync('token');
  const userInfo = wx.getStorageSync('userInfo');
  
  // 仅在开发环境输出调试信息

  
  return {
    token,
    userInfo,
    isLoggedIn: checkLoginStatus(),
    tokenLength: token ? token.length : 0
  };
};

module.exports = {
  userApi,
  getRsaPublicKey,
  login,
  logout,
  fetchUserInfo,
  checkLoginStatus,
  requireLogin,
  testTokenStatus
};